package goods

import (
	"enjoy_xxz/formdata"
	"enjoy_xxz/internal/model/database/mysql"
	"enjoy_xxz/pkg"
	"errors"
	"fmt"
	"gorm.io/gorm"
)

// 商品属性SKU表的结构体
type GoodsSku struct {
	gorm.Model
	Img         string `gorm:"type:json;comment:商品图片链接;"`
	ProValueID1 int64  `gorm:"type:int;comment:属性值1的ID;"`
	ProValueID2 int64  `gorm:"type:int;comment:属性值2的ID;"`
	ProValueID3 int64  `gorm:"type:int;comment:属性值3的ID;"`
	Price       string `gorm:"type:decimal(10,2);comment:商品价格;"`
	VipPrice    string `gorm:"type:decimal(10,2);comment:VIP价格;"`
	Stock       int64  `gorm:"type:int;comment:商品库存;"`
	GoodsID     int64  `gorm:"type:int;comment:关联的商品ID;"`
}

// 修改库存
func (g *GoodsSku) UpdateStockByGoodsId(num int) error {
	return mysql.WithMysql(func(db *gorm.DB) error {
		return db.Model(g).Where("id = ?", g.ID).Update("stock", gorm.Expr("stock - ?", num)).Error
	})
}

// 查询详情
func (g *GoodsSku) GetGoodsSkuInfoBySkuID(ids []int64) ([]GoodsSku, error) {
	var list []GoodsSku
	return list, mysql.WithMysql(func(db *gorm.DB) error {
		return db.Where("id in (?)", ids).Find(&list).Error
	})
}

// 查询商品信息
func (g *GoodsSku) GetGoodsSkuByGoodsId(ids []int64) (gg formdata.OrderGoodsInfos, err error) {
	var list []GoodsSku
	return gg, mysql.WithMysql(func(db *gorm.DB) error {
		err = db.Where("id in (?)", ids).Find(&list).Error
		if err != nil {
			return err
		}
		infoMap := make(map[int64]GoodsSku)
		var idss []int64
		for _, val := range list {
			idss = append(idss, val.GoodsID)
			infoMap[val.GoodsID] = val
		}
		//查询商品表
		goo := Goods{}
		goodsInfo, err := goo.GoodsDetailByIds(idss)
		if err != nil {
			return err
		}

		for _, val := range goodsInfo {
			if res, ok := infoMap[int64(val.ID)]; ok {
				images := pkg.GetImages(val.Img)
				gg = formdata.OrderGoodsInfos{
					GoodsId:          int64(val.ID),
					PropertyValueId1: res.ProValueID1,
					PropertyValueId2: res.ProValueID2,
					PropertyValueId3: res.ProValueID3,
					SkuId:            int64(res.ID),
					Title:            val.Title,
					Img:              images,
					Price:            res.Price,
				}
			}
		}

		return nil
	})
}

// 根据属性值查询商品的详情信息
func (g *GoodsSku) GetGoodsDetailByVal(image []string) (info formdata.GoodsSkuInfo, err error) {
	return info, mysql.WithMysql(func(db *gorm.DB) error {
		// 初始化查询条件
		query := db.Where("goods_id = ?", g.GoodsID)

		// 使用map存储属性值和对应的字段名
		proValues := map[string]int64{
			"pro_value_id1": g.ProValueID1,
			"pro_value_id2": g.ProValueID2,
			"pro_value_id3": g.ProValueID3,
		}

		// 统计非零属性值的数量
		nonZeroCount := 0
		for key, value := range proValues {
			if value != 0 {
				nonZeroCount++
				query = query.Where(key+" = ?", value)
			}
		}

		// 检查是否至少传递了两个属性值
		if nonZeroCount < 2 {
			return fmt.Errorf("至少需要传递两个属性值")
		}

		// 如果没有指定任何属性值，则按价格排序取最低价格商品
		if nonZeroCount == 0 {
			fmt.Println("默认查询")
			query = query.Order("price")
		}

		// 执行查询
		err = query.First(&g).Error
		if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
			return err
		}

		info = formdata.GoodsSkuInfo{
			SkuID:       int64(g.ID),
			ProValueID1: g.ProValueID1,
			ProValueID2: g.ProValueID2,
			ProValueID3: g.ProValueID3,
			Price:       g.Price,
			VipPrice:    g.VipPrice,
			Stock:       g.Stock,
			GoodsID:     g.GoodsID,
			Image:       image,
		}
		return nil
	})
}
